package com.gilight.base.listener;

import com.gilight.base.common.BzdmConstant;
import com.gilight.base.dao.SysUserAccessLogMapper;
import com.gilight.base.model.SysUser;
import com.gilight.base.model.SysUserAccessLog;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MySessionListener implements SessionListener {
    private final AtomicInteger sessionCount = new AtomicInteger(0);

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysUserAccessLogMapper sysUserAccessLogMapper;

    @Override
    public void onStart(Session session) {
        sessionCount.incrementAndGet();
//        System.out.println("登录+1=="+sessionCount.get());
    }

    @Override
    public void onStop(Session session) {
        sessionCount.decrementAndGet();
        //System.out.println("登录退出-1=="+sessionCount.get());
        this.logout(session);
    }

    @Override
    public void onExpiration(Session session) {
        sessionCount.decrementAndGet();
        //System.out.println("登录过期-1=="+sessionCount.get());
        this.logout(session);
    }

    public int getSessionCount() {
        return sessionCount.get();
    }

    private void logout(Session session){
        Object obj = redisTemplate.opsForValue().get(BzdmConstant.USER_SESSION_PER +session.getId());
        if(obj!=null){
            try{
                SysUser sysUser = (SysUser)obj;
                SysUserAccessLog sysUserAccessLog = new SysUserAccessLog();
                sysUserAccessLog.setUserCode(sysUser.getUserCode());
                sysUserAccessLog.setUserName(sysUser.getUserName());
                sysUserAccessLog.setType(2);
                sysUserAccessLog.setCreateTime(session.getLastAccessTime());
                sysUserAccessLog.setIp(session.getHost());
                sysUserAccessLogMapper.insertSelective(sysUserAccessLog);
                redisTemplate.delete(BzdmConstant.USER_SESSION_PER +session.getId());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
